import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const state = {
    chatRecord: [],
    active_id: null
};

const getters = {
    getChatRecord(state) {
        return state.chatRecord
    },
    getActive_id(state) {
        return state.active_id
    }
};

const mutations = {
    pushChatRecord(state, data) {
        let aRecord = data,
            allChat = state.chatRecord;
        let curUserAllData = allChat.find((item, index) => {
            return item.friend_client_id === data.active_id
        });
        
        if (curUserAllData) {
            curUserAllData.data.push(data)
        } else {
            let obj = {},
                ary = [];
            obj.friend_client_id = data.active_id;
            obj.data = ary;
            ary.push(data);
            allChat.push(obj);
        }
        localStorage.setItem(state.active_id, JSON.stringify(state.chatRecord.slice(-20)));
    },
    pushChatRecordMy(state, data) {
        let aRecord = data.data,
            allChat = state.chatRecord;
    },
    setChatRecords(state, data) {
        if (data) {
            state.chatRecord = data
        }
    },
    setActive_id(state,active_id){
        state.active_id = active_id
    }
};

const actions = {
    newChatRecord(context, data) {
        context.commit('pushChatRecord', data)
    },
    newChatRecordMy(context, data) {
        context.commit('pushChatRecordMy', data)
    },
    records(context, data) {
        context.commit('setChatRecords', data)
    },
    initActive_id(context, active_id){
        context.commit('setActive_id', active_id)
    }
};

const store = new Vuex.Store({
    state,
    getters,
    mutations,
    actions
});

export default store;
